package com.hjzd.ai.smartpractice.util;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import com.hjzd.ai.smartpractice.websocket.ChatCompletionChunkResponse;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.List;

public class ConversationUtil {

    private static final RestTemplate restTemplate = new RestTemplate();
    private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
            .setLongSerializationPolicy(LongSerializationPolicy.STRING).disableHtmlEscaping().create();

    private static WebClient webClient;

    static {
        // 初始化 WebClient
        webClient = WebClient.builder()
                .defaultHeaders(headers -> {
                    headers.set(HttpHeaders.ACCEPT, "*/*");
                    headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br");
                    headers.set(HttpHeaders.CONNECTION, "keep-alive");
                    headers.set(HttpHeaders.USER_AGENT, "PostmanRuntime-ApipostRuntime/1.1.0");
                    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                })
                .build();
    }

    /**
     * 启动对话，获取 conversation_id
     *
     * @param serviceUrl 服务 URL
     * @return 返回 conversation_id
     */
    public static String startConversation(String serviceUrl) {
        String url = serviceUrl + "/start_conversation"; // 使用传入的 URL

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "*/*");
        headers.set("Accept-Encoding", "gzip, deflate, br");
        headers.set("Connection", "keep-alive");
        headers.set("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0");

        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        try {
            // 发送GET请求
            ResponseEntity<ConversationResponse> response = restTemplate.exchange(
                    url, HttpMethod.GET, requestEntity, ConversationResponse.class);

            // 检查响应状态码
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return response.getBody().getConversation_id();
            } else {
                throw new RuntimeException("请求失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 发送 POST 请求并处理流式响应
     *
     * @param serviceUrl 对话服务的 URL
     * @param conversationId 对话 ID
     * @return 流式响应内容
     */
    public static Flux<String> sendPrologueRequest(String serviceUrl, String conversationId) {
        // 请求体
        String requestBody = String.format("{\"conversation_id\":\"%s\"}", conversationId);

        // 发送 POST 请求并处理流式响应
        return webClient.post()
                .uri(serviceUrl + "/prologue") // 使用传入的 URL
                .bodyValue(requestBody)
                .accept(MediaType.TEXT_EVENT_STREAM) // 接受流式响应
                .retrieve()
                .bodyToFlux(String.class)
                .filter(content -> !content.isEmpty()) // 过滤空内容
                .map(content -> content.replaceFirst("data: ", "")); // 去掉 "data: " 前缀
    }

    /**
     * 发送 POST 请求到 /chat 接口
     *
     * @param serviceUrl 对话服务的 URL
     * @param requestBody 请求体
     * @return 流式响应内容
     */
    public static Flux<String> sendChatRequest(String serviceUrl, ObjectNode requestBody) {
        // 发送 POST 请求并处理流式响应
        return webClient.post()
                .uri(serviceUrl + "/chat") // 使用传入的 URL
                .bodyValue(requestBody)
                .accept(MediaType.TEXT_EVENT_STREAM) // 接受流式响应
                .retrieve()
                .bodyToFlux(String.class)
                .filter(content -> !content.isEmpty()); // 过滤空内容
    }

    /**
     * 启动与客户的对话，获取 conversation_id
     *
     * @param serviceUrl 服务 URL
     * @return 返回 conversation_id
     */
    public static String startConversationWithCustomer(String serviceUrl) {
        String url = serviceUrl + "/start_conversation_customer"; // 使用传入的 URL

        // 创建请求实体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON));

        // 硬编码请求体
        String requestBody = "{\"customer_info\":{\"姓名\":\"周泰\",\"逾期时间\":\"98天\",\"欠款金额\":\"13500元\",\"住址\":\"上海市浦东新区\",\"电话\":\"18101845352\"}}";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送 POST 请求
            ResponseEntity<CustomerConversationResponse> response = restTemplate.exchange(
                    url, HttpMethod.POST, requestEntity, CustomerConversationResponse.class);

            // 检查响应状态码
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return response.getBody().getConversation_id();
            } else {
                throw new RuntimeException("请求失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 请求模拟客户接口
     *
     * @param serviceUrl 对话服务的 URL
     * @param requestBody 请求体
     * @return 流式响应内容
     */
    public static Flux<String> sendChatCustomerRequest(String serviceUrl, ObjectNode requestBody) {
        // 发送 POST 请求并处理流式响应
        return webClient.post()
                .uri(serviceUrl + "/chat_customer") // 使用传入的 URL
                .bodyValue(requestBody)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class)
                .filter(content -> !content.isEmpty()); // 过滤空内容
    }

    /**
     * 解析 JSON 响应，提取 content 字段
     *
     * @param json 原始 JSON 数据
     * @return 提取的 content 字段
     */
    private static String parseResponse(String json) {
        try {
            if (!"[DONE]".equals(json)) {
                ChatCompletionChunkResponse response = GSON.fromJson(json, ChatCompletionChunkResponse.class);
                if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                    return response.getChoices().get(0).getDelta().getContent();
                }
            }
        } catch (Exception e) {
            System.err.println("JSON 解析失败: " + e.getMessage());
        }
        return "";
    }

    // 定义响应实体类
    private static class ConversationResponse {
        @JsonProperty("conversation_id")
        private String conversation_id;

        public String getConversation_id() {
            return conversation_id;
        }

        public void setConversation_id(String conversation_id) {
            this.conversation_id = conversation_id;
        }
    }

    // 定义客户对话启动响应实体类
    private static class CustomerConversationResponse {
        @JsonProperty("conversation_id")
        private String conversation_id;

        public String getConversation_id() {
            return conversation_id;
        }

        public void setConversation_id(String conversation_id) {
            this.conversation_id = conversation_id;
        }
    }
}
